package service

import (
	"sdc/repository/db/model"
	"gorm.io/gorm"
)

type AdminService struct {
	db *gorm.DB
}

func NewAdminService(db *gorm.DB) *AdminService {
	return &AdminService{db: db}
}

// CheckPermission 检查用户权限
func (s *AdminService) CheckPermission(userID uint64, permCode string) bool {
	var count int64
	s.db.Model(&model.RolePermission{}).
		Joins("JOIN user_roles ON role_permissions.role_id = user_roles.role_id").
		Joins("JOIN permissions ON role_permissions.permission_id = permissions.id").
		Where("user_roles.user_id = ? AND permissions.code = ? AND permissions.status = 1",
			userID, permCode).
		Count(&count)
	return count > 0
}

// ListUsers 用户列表
func (s *AdminService) ListUsers(keyword string, page, pageSize int) (users []model.User, total int64, err error) {
	offset := (page - 1) * pageSize
	query := s.db.Model(&model.User{})

	if keyword != "" {
		query = query.Where(
			"username LIKE ? OR phone LIKE ? OR email LIKE ?",
			"%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%",
		)
	}

	// 统计总数
	err = query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 查询用户列表
	err = query.Select("id, username, real_name, phone, email, status, created_at, updated_at").
		Offset(offset).Limit(pageSize).
		Order("created_at DESC").
		Find(&users).Error

	return users, total, err
}

// UpdateUserStatus 更新用户状态
func (s *AdminService) UpdateUserStatus(userID uint64, status int8) error {
	return s.db.Model(&model.User{}).
		Where("id = ?", userID).
		Update("status", status).Error
}

